﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Web.Syndication;

namespace DesdemonaDespairLib
{
    public class DesdemonaSyndicationItem
    {
        public DesdemonaSyndicationItem( SyndicationItem item )
        {
            this.Title = item.Title.Text;

            XmlDocument itemDocument = item.GetXmlDocument( SyndicationFormat.Atom10 );
            this.id = GetId( itemDocument );
            this.published = GetPublicationDate( itemDocument );
            this.url = GetUrl( item );
            this.content = GetContent( itemDocument );
            this.Image = ParseImgTag( this.content );

            //this.FirstParagraph = GetFirstParagraph( this.content );

            //XmlDocument doc = ParseContent( this.content );

        }

        public string id { get; private set; }
        public DateTime updated { get; private set; }
        public string content { get; private set; }
        public DateTime published { get; private set; }
        public Uri url { get; private set; }
        public string Title { get; private set; }

        public string FirstParagraph { get; private set; }
        public Uri imageUrl { get; private set; }
        public ItemImage Image { get; private set; }

        private static string GetId( XmlDocument itemDocument )
        {
            return GetNodeValue( idElementName, itemDocument );
        }

        private static string GetContent( XmlDocument itemDocument )
        {
            string content = GetNodeValue( contentElementName, itemDocument );

            // Style the content.
            string contentHtml = htmlBodyStyle + content + htmlBodyStyleCloseTags;

            return contentHtml;
        }

        private static DateTime GetPublicationDate( XmlDocument itemDocument )
        {
            DateTime pubDate = DateTime.MinValue;

            string pubDateString = GetNodeValue( publishedElementName, itemDocument );

            if( pubDateString != null )
            {
                try
                {
                    pubDate = DateTime.Parse( pubDateString );
                }
                catch( Exception ex )
                {
                    Debug.WriteLine( ex.ToString() );
                }
            }

            return pubDate;
        }

        private static Uri GetUrl( SyndicationItem item )
        {
            return item.Links[4].Uri;
        }

        private string GetFirstParagraph( string content )
        {

            string firstParagraph = null;



            return firstParagraph;

        }

        private static string GetNodeValue( string elementName, XmlDocument itemDocument )
        {
            string value = null;
            try
            {
                value = itemDocument.GetElementsByTagName( elementName )[0].FirstChild.NodeValue as string;
            }
            catch( Exception ex )
            {
                Debug.WriteLine( ex.ToString() );
            }

            return value;
        }


        private static XmlDocument ParseContent( string content )
        {
            XmlDocument contentDocument = null;

            try
            {
                ItemImage itemImage = ParseImgTag( content );

                //string scrubbedContent = content.Replace( "& ", "and " );
                //XmlLoadSettings loadSettings = new XmlLoadSettings();
                //loadSettings.ProhibitDtd = false;
                //loadSettings.ResolveExternals = false;
                //loadSettings.ValidateOnParse = false;

                //contentDocument = new XmlDocument();
                //contentDocument.LoadXml( scrubbedContent, loadSettings );
            }
            catch( Exception ex )
            {
                Debug.WriteLine( ex.ToString() );
            }

            return contentDocument;
        }

        private static ItemImage ParseImgTag( string content )
        {
            ItemImage itemImage = null;

            int openIndex = content.IndexOf( imgOpenTag );

            if( openIndex > 0 )
            {
                int closeIndex = content.IndexOf( ">", openIndex );

                if( closeIndex > 0 )
                {
                    try
                    {
                        string imgTag = content.Substring( openIndex, closeIndex - openIndex + 1 );
                        string imgElement = imgTag.Replace( ">", "/>" );
                        string imgElementScrubbed = imgElement.Replace( '&', ' ' ); 

                        XmlLoadSettings loadSettings = new XmlLoadSettings();
                        loadSettings.ProhibitDtd = false;
                        loadSettings.ResolveExternals = false;
                        loadSettings.ValidateOnParse = false;

                        XmlDocument imgDocument = new XmlDocument();
                        imgDocument.LoadXml( imgElementScrubbed, loadSettings );

                        string alt = String.Empty;
                        string src = String.Empty;
                        string width = String.Empty;
                        string height = String.Empty;
                        var altAttribute = imgDocument.FirstChild.Attributes.GetNamedItem( "alt" );
                        var srcAttribute = imgDocument.FirstChild.Attributes.GetNamedItem( "src" );
                        var widthAttribute = imgDocument.FirstChild.Attributes.GetNamedItem( "width" );
                        var heightAttribute = imgDocument.FirstChild.Attributes.GetNamedItem( "height" );
                        alt = altAttribute != null ? altAttribute.NodeValue as string : String.Empty;
                        src = srcAttribute != null ? srcAttribute.NodeValue as string : String.Empty;
                        width = widthAttribute != null ? widthAttribute.NodeValue as string : String.Empty;
                        height = heightAttribute != null ? heightAttribute.NodeValue as string : String.Empty;

                        itemImage = new ItemImage( alt, src, width, height );
                    }
                    catch( Exception ex )
                    {
                        Debug.WriteLine( ex.ToString() );
                    }
                }
            }

            return itemImage;
        }



        const string titleElementName = "title";
        const string idElementName = "id";
        const string updatedElementName = "updated";
        const string contentElementName = "content";
        const string publishedElementName = "published";
        const string authorElementName = "author";
        const string categoryElementName = "category";
        const string linkElementName = "link";
        const string thumbnailElementName = "thumbnail";
        const string totalElementName = "total";

        const string htmlBodyStyle = "<html><body style=\"color:white;background-color:black;font-family:Segoe UI;\">";
        const string htmlBodyStyleCloseTags = "</html></body>";
        const string imgOpenTag = "<img";

    }


    //itemDocument.childNodes[0] entry
    //[0]title XmlElement
    //id
    //updated
    //content
    //published
    //author
    //category
    //category
    //...
    //link
    //link
    //thumbnail
    //total

}
